<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>18可编辑表格</title>
	<style>
		table{width:90%;border:1px solid #ddd;border-collapse: collapse;}
		td,th{border:1px solid #ddd;}
		td input{width:100%;box-sizing: border-box;}
	</style>
	<script>
		window.onload = function(){
			// 表格可编辑
			// 点击单元格时，替换成input标签

			// 获取所有的单元格
			var datalist = document.getElementsByClassName('datalist')[0];
			var td = datalist.getElementsByTagName('td');

			// 给所有td绑定点击事件
			for(var i=0;i<td.length;i++){
				td[i].onclick = function(){
					// 创建一个变量保存当前td，方便在失去焦点是用
					var currentTd = this;

					// 先创建一个输入框
					var input = document.createElement('input');
					input.type = 'text';
					input.value = this.innerHTML;

					this.innerText = '';
					this.appendChild(input);

					// 自动获得焦点
					input.focus();

					// 表单失去焦点时把内容写回td
					input.onblur = function(e){
						// 把表单的内容写入当前td
						currentTd.innerText = input.value;
					}

					input.onclick = function(e){

						// 阻止冒泡
						e.stopPropagation();
					}
				}
			}
		}
	</script>
</head>
<body>
	<table class="datalist">
		<thead>
			<tr>
				<th>序号</th>
				<th>标题1</th>
				<th>标题2</th>
				<th>标题3</th>
				<th>标题4</th>
				<th>标题5</th>
				<th>操作</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>1</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>2</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>3</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>4</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>5</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>6</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>7</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>8</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>9</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
			<tr>
				<td>10</td>
				<td>单元格1</td>
				<td>单元格2</td>
				<td>单元格3</td>
				<td>单元格4</td>
				<td>单元格5</td>
				<td><button>删除</button></td>
			</tr>
		</tbody>
		
	</table>
</body>
</html>